<template>
  <el-dialog
    v-model="visible"
    title="条件组合"
    width="1000px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="condition-builder">
      <span v-if="loading">加载中...</span>
      <Builder v-else-if="fields.length" ref="builderRef" :model="model" :fields="fields" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="left"></div>
        <div class="right">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import Builder from './BuilderItem.vue'
import { check } from './index.js'

export default {
  name: 'DialogConditionBuilder',
  components: {
    Builder
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    default: {
      type: Object,
      default: () => ({})
    },
    api: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'result'],
  data() {
    return {
      model: {
        id: Date.now(),
        combinator: 'and',
        children: []
      },
      fields: [],
      loading: false,
      builderRef: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.modelValue
      },
      set(val) {
        this.$emit('update:modelValue', val)
      }
    }
  },
  watch: {
    modelValue: {
      handler(val) {
        if (this.default) {
          this.model = this.default
        }
        if (val && this.api) {
          this.loading = true
          fetch(this.api).then((response) => {
            response.json().then((res) => {
              this.loading = false
              if (res.code === 200) {
                this.fields = res.data.rows
                check(this.model, this.fields)
              } else {
                console.log(res.message)
              }
            })
          })
        }
      }
    }
  },
  methods: {
    handleConfirm() {
      const res = check(this.model, this.fields)
      this.$emit('result', {
        data: this.model,
        valid: !res
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    .left {
      flex: 1;
    }
  }
</style>
